package com.qdhh.enrollment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qdhh.enrollment.domain.Faq;
import com.qdhh.enrollment.dto.FaqDTO;
import com.qdhh.enrollment.mapper.FaqMapper;
import com.qdhh.enrollment.service.FaqService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class FaqServiceImpl implements FaqService {

    private final FaqMapper faqMapper;

    @PostConstruct
    public void initSeed() {
        try {
            seedIfEmpty();
        } catch (Exception e) {
            log.warn("FAQ seed skipped: {}", e.getMessage());
        }
    }

    @Override
    public List<FaqDTO> search(String keyword, Integer limit) {
        LambdaQueryWrapper<Faq> wrapper = new LambdaQueryWrapper<Faq>()
            .eq(Faq::getEnabled, 1)
            .orderByAsc(Faq::getOrderNum)
            .orderByAsc(Faq::getCreatedAt);

        if (StringUtils.hasText(keyword)) {
            String[] tokens = keyword.trim().split("\\s+");
            for (String token : tokens) {
                String tk = token.trim();
                if (!StringUtils.hasText(tk)) {
                    continue;
                }
                wrapper.and(w -> w.like(Faq::getQuestion, tk)
                    .or()
                    .like(Faq::getAnswer, tk)
                    .or()
                    .like(Faq::getTags, tk));
            }
        }

        if (limit != null && limit > 0) {
            wrapper.last("LIMIT " + limit);
        }

        List<Faq> faqs = faqMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(faqs)) {
            return List.of();
        }
        return faqs.stream().map(this::toDto).collect(Collectors.toList());
    }

    @Override
    public void seedIfEmpty() {
        Long count = faqMapper.selectCount(null);
        if (count != null && count > 0) {
            return;
        }
        LocalDateTime now = LocalDateTime.now();
        List<Faq> seeds = Arrays.asList(
            buildFaq("seed-faq-arrival-materials", "入学当天需要携带哪些材料？",
                "请携带录取通知书、身份证、近期照片以及缴费凭证，办理入学手续时需出示。",
                "报到,材料", 5, now),
            buildFaq("seed-faq-dorm-electric", "宿舍可以使用哪些电器？",
                "小功率电器如吹风机、电水壶允许使用，高功率电磁炉等需到公共区域或禁止使用。",
                "宿舍,电器", 10, now),
            buildFaq("seed-faq-visa-check", "国际学生在入学前需完成哪些签证检查？",
                "需确认学生签证有效期，并在抵校后十日内前往国际合作处办理居留许可。",
                "国际生,签证,visa", 15, now),
            buildFaq("seed-faq-aid-proof", "申请助学贷款需要哪些证明材料？",
                "需提供家庭经济困难证明、身份证复印件、录取通知书及学校统一填写的申请表。",
                "资助,贷款,材料", 20, now)
        );
        seeds.forEach(faqMapper::insert);
    }

    private Faq buildFaq(String id, String question, String answer, String tags,
                         int orderNum, LocalDateTime createdAt) {
        Faq faq = new Faq();
        faq.setId(id);
        faq.setQuestion(question);
        faq.setAnswer(answer);
        faq.setTags(tags);
        faq.setOrderNum(orderNum);
        faq.setEnabled(1);
        faq.setCreatedAt(createdAt);
        return faq;
    }

    private FaqDTO toDto(Faq faq) {
        FaqDTO dto = new FaqDTO();
        dto.setId(faq.getId());
        dto.setQuestion(faq.getQuestion());
        dto.setAnswer(faq.getAnswer());
        dto.setTags(faq.getTags());
        dto.setOrderNum(faq.getOrderNum());
        return dto;
    }
}
